#include "Character.h"
using namespace std;

Character::Character()
	:mAttacker(0)
{
	mesh = xCreateSphere();
	lastKick = timeGetTime();
}

Character::Character( float x, float y, float z )
	:mAttacker(0)
{
	mesh = xCreateSphere();
	xPositionEntity(mesh, x, y, z);
	mDestination = GetPosition();
	lastKick = timeGetTime();
}

bool Character::Attaced()
{
	return mAttacker? true:false;
}

void Character::SetDirection(const Vec3D& dir)
{
	float pitch = xVectorPitch(dir.x, dir.y, dir.z);
	float yaw  = xVectorYaw(dir.x, dir.y, dir.z);
	float roll = 0;
	xRotateEntity(mesh, pitch, yaw, roll,true);
}

Character * Character::SelectedEnemy(const vector<Character*>& enemies)
{
	for(size_t i = 0; i < enemies.size(); ++i)
	{
		if(DistanceTo(enemies[i]->GetPosition()) < 3)
		{
			return enemies[i];
		}
	}
	return 0;
}

void Character::MoveToPoint(const Vec3D& dist)
{
	Vec3D position = GetPosition();
	Vec3D direction(position, dist);

	SetDirection(direction);
	xMoveEntity(mesh, 0, 0, mAttributes.Speed());
}

void Character::DealDamage(Character* target)
{
	if ((timeGetTime() - lastKick) > mAttributes.AttackSpeed() * 100)
	{
		target->mAttributes.TakeDamage(mAttributes.Str() + mAttributes.Damage());
		lastKick = timeGetTime();
	}
	target->mAttacker = this;
}

Vec3D Character::GetPosition() const
{
	return Vec3D(xEntityX(mesh, true), xEntityY(mesh, true), xEntityZ(mesh, true));
}

Vec3D Character::GetDestination() const
{
	return mDestination;
}

float Character::DistanceTo(const Vec3D& point) const
{
	return Vec3D(GetPosition(), point).Lenght();
}

bool Character::InPosition(const Vec3D& position) const
{
	return DistanceTo(position) < 0.5 ? true:false;
}

Character::~Character()
{

}

void Character::Move()
{
	Vec3D position = GetPosition();
	if (!InPosition(mDestination))
	{
		Vec3D direction(position, mDestination);

		SetDirection(direction);
		xMoveEntity(mesh, 0, 0, mAttributes.Speed());
	}
}

bool Character::IsDead()
{
	return mAttributes.Health() == 0;
}
